package main

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"time"

	_ "github.com/mattn/go-sqlite3"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	tmt "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/tmt/v20180321"
)

// 定义对话结构
type Conversation struct {
	ID       string    `json:"id"`       // 对话ID
	Title    string    `json:"title"`    // 对话标题
	Messages []Message `json:"messages"` // 聊天记录
}

// 定义消息结构
type Message struct {
	Text          string `json:"text"`          // 消息内容
	IsUser        bool   `json:"isUser"`        // 是否是用户消息
	IsHighlighted bool   `json:"isHighlighted"` // 是否高亮
}

// App struct
type App struct {
	ctx                   context.Context
	SecretId              string
	SecretKey             string
	db                    *sql.DB
	Conversations         []Conversation `json:"conversations"`         // 所有对话
	CurrentConversationID string         `json:"currentConversationId"` // 当前选中的对话ID
}

// NewApp creates a new App application struct
func NewApp() *App {
	result := &App{
		Conversations: []Conversation{},
		db:            initDB(),
		SecretId:      os.Getenv("TENCENT_SECRET_ID"),
		SecretKey:     os.Getenv("TENCENT_SECRET_KEY"),
	}
	result.Conversations = loadConversations(result.db)
	if len(result.Conversations) == 0 {
		result.NewConversation()
	} else {
		result.CurrentConversationID = result.Conversations[0].ID // 默认选中第一个对话
	}
	return result
}

// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
	a.ctx = ctx
}

// shutdown
func (a *App) shutdown(ctx context.Context) {
	log.Println("Shutting down app")
	for _, conversation := range a.Conversations {
		saveConversation(a.db, conversation)
	}
	a.db.Close()
}

// 新建对话
func (a *App) NewConversation() Conversation {
	conversation := Conversation{
		ID:       generateID(), // 生成唯一ID
		Title:    "新对话",
		Messages: []Message{},
	}
	a.Conversations = append(a.Conversations, conversation)
	return conversation
}

// 删除对话
func (a *App) DeleteConversation(conversationID string) {
	for i, conversation := range a.Conversations {
		if conversation.ID == conversationID {
			a.Conversations = append(a.Conversations[:i], a.Conversations[i+1:]...)
			break
		}
	}
}

// 获取对话列表
func (a *App) GetConversations() []Conversation {
	return a.Conversations
}

// 设置当前对话
func (a *App) SetCurrentConversation(id string) {
	a.CurrentConversationID = id
}
func (a *App) UpdateConversationTitle(conversationID string, title string) {
	for i, conv := range a.Conversations {
		if conv.ID == conversationID {
			a.Conversations[i].Title = title
			break
		}
	}
}

// 获取当前对话的聊天记录
func (a *App) GetCurrentConversationMessages() []Message {
	for _, conv := range a.Conversations {
		if conv.ID == a.CurrentConversationID {
			return conv.Messages
		}
	}
	return []Message{}
}

// 添加消息到当前对话
func (a *App) AddMessage(text string, isUser bool) {
	for i, conv := range a.Conversations {
		if conv.ID == a.CurrentConversationID {
			a.Conversations[i].Messages = append(conv.Messages, Message{Text: text, IsUser: isUser})
			break
		}
	}
}
func (a *App) DeleteMessages(conversationID string, index int) {
	for i, conv := range a.Conversations {
		if conv.ID == conversationID {
			// 删除用户消息和对应的翻译
			a.Conversations[i].Messages = append(conv.Messages[:index], conv.Messages[index+2:]...)
			break
		}
	}
}

// 更新消息的高亮状态
func (a *App) UpdateMessageHighlight(conversationID string, messageIndex int, isHighlighted bool) {
	for i, conv := range a.Conversations {
		if conv.ID == conversationID && messageIndex < len(conv.Messages) {
			a.Conversations[i].Messages[messageIndex].IsHighlighted = isHighlighted
			break
		}
	}
}

// 生成唯一ID（简单示例）
func generateID() string {
	return fmt.Sprintf("%d", time.Now().UnixNano())
}

// 获取数据存储路径
func getDataPath() string {
	// 获取用户配置目录
	configDir, err := os.UserConfigDir()
	if err != nil {
		fmt.Println("无法获取配置目录:", err)
		return "./conversations.db" // 默认当前目录
	}

	// 创建应用程序数据目录
	appDataDir := filepath.Join(configDir, "chat-translator")
	if err := os.MkdirAll(appDataDir, 0755); err != nil {
		fmt.Println("无法创建数据目录:", err)
		return "./conversations.db" // 默认当前目录
	}

	// 返回数据库文件路径
	return filepath.Join(appDataDir, "conversations.db")
}

// 初始化数据库
func initDB() *sql.DB {
	dbPath := getDataPath()
	db, err := sql.Open("sqlite3", dbPath)
	if err != nil {
		log.Fatal(err)
	}

	// 创建对话表
	_, err = db.Exec(`
	  CREATE TABLE IF NOT EXISTS conversations (
		id TEXT PRIMARY KEY,
		title TEXT,
		messages TEXT
	  )
	`)
	if err != nil {
		log.Fatal(err)
	}

	return db
}

// 保存对话到数据库
func saveConversation(db *sql.DB, conv Conversation) {
	messagesJSON, _ := json.Marshal(conv.Messages)
	_, err := db.Exec(`
	  INSERT OR REPLACE INTO conversations (id, title, messages)
	  VALUES (?, ?, ?)
	`, conv.ID, conv.Title, string(messagesJSON))
	if err != nil {
		log.Fatal(err)
	}
}

// 从数据库加载对话
func loadConversations(db *sql.DB) []Conversation {
	rows, err := db.Query("SELECT id, title, messages FROM conversations")
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	var conversations []Conversation
	for rows.Next() {
		var id, title, messagesJSON string
		rows.Scan(&id, &title, &messagesJSON)

		var messages []Message
		json.Unmarshal([]byte(messagesJSON), &messages)

		conversations = append(conversations, Conversation{
			ID:       id,
			Title:    title,
			Messages: messages,
		})
	}

	return conversations
}

func (a *App) Translate(text string) (string, error) {
	sourceLang := "en"
	targetLang := "zh"
	credential := common.NewCredential(a.SecretId, a.SecretKey)
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "tmt.tencentcloudapi.com"

	client, _ := tmt.NewClient(credential, "ap-guangzhou", cpf)
	request := tmt.NewTextTranslateRequest()
	request.SourceText = common.StringPtr(text)
	request.Source = common.StringPtr(sourceLang)
	request.Target = common.StringPtr(targetLang)
	request.ProjectId = common.Int64Ptr(0)

	response, err := client.TextTranslate(request)
	if err != nil {
		if sdkErr, ok := err.(*errors.TencentCloudSDKError); ok {
			log.Printf("API error: %s", sdkErr.Message)
		}
		return "", err
	}

	return *response.Response.TargetText, nil
}
